#import "MyNetworkListenerPlugin.h"
#import "NetworkListener.h"
#import "callback/NetworkChangeCallback.h"
#define EVENT_CHANNEL @"my.flutter.event/network"

@interface MyNetworkListenerPlugin()<NetworkChangeCallback,FlutterStreamHandler>
@property (nonatomic,strong) FlutterEventSink myEventSink;//flutter中订阅了接收我发送的消息的观察者,因为ios取消监听的回调函数没有传eventSink对象进来，所以就不能用list来储存eventLink
@end

@implementation MyNetworkListenerPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
   MyNetworkListenerPlugin* instance = [[MyNetworkListenerPlugin alloc] init];
   FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:EVENT_CHANNEL binaryMessenger:[registrar messenger]];// 初始化FlutterEventChannel对象
   [eventChannel setStreamHandler:instance];
   instance.networkListener=[NetworkListener new];//生成网络监听对象
   [instance.networkListener setNetChangeCallback:instance];//设置回调函数
}

//网络状态改变之后调用的方法
- (void)networkStateChangeCallback:(BOOL)isAvaliable{
    if(isAvaliable){
        NSDictionary<NSString *,id> * successData=[[NSDictionary alloc]
                                                   initWithObjectsAndKeys:
                                                   @"80001", @"code",nil];//因为NSDictionary不可改变，所以一定要这样初始化
        [self sendDataToFlutter:successData];
    }else
        [self sendDataToFlutter:[FlutterError errorWithCode:@"90001" message:@"网络连接不可用" details:nil]];
}

-(void)sendDataToFlutter:(id) data{//向flutter发送数据
    if(self.myEventSink!=nil)
        self.myEventSink(data);
}

#pragma mark - FlutterStreamHandler
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                       eventSink:(FlutterEventSink)eventSink{//当flutter向监听我们的channel时调用的函数
    self.myEventSink=eventSink;//设置观察者
    [self.networkListener currentNetworkStateIsAvailable];//先直接向flutter发送网络状态,让其有个初始值
    return nil;
}

- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {//flutter取消对我们的监听时调用的函数
    self.myEventSink=nil;//删除观察者
    return nil;
}
@end
